<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head><link rel="stylesheet" type="text/css" href="description/Combined.css,0:HeaderFooterSprite,0:Header.NonMtps,1:LinkList;/Areas/Centers/Themes/StandardDevCenter/Content:0,/Areas/Epx/Themes/Base/Content:1&amp;amp;hashKey=C9973DA951AE6202C9B348379A1BE49D" xmlns="http://www.w3.org/1999/xhtml" />
<link type="text/css" rel="stylesheet" xmlns="http://www.w3.org/1999/xhtml" />
<link rel="stylesheet" type="text/css" href="description/a7d1e078-8570-47da-a87b-ff462dfc958dCombined.css,0:HeaderFooterSprite,0:Footer.NonMtps,1:LinkList;/Areas/Centers/Themes/StandardDevCenter/Content:0,/Areas/Epx/Themes/Base/Content:1&amp;amp;hashKey=F576C687BC536B84D6E5B3246EE39B49" xmlns="http://www.w3.org/1999/xhtml" />
<link type="text/css" rel="stylesheet" xmlns="http://www.w3.org/1999/xhtml" />

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Design Patterns - Service Locator Pattern (Inversion of Control &amp; Unity Blocks)</title>
        <link href="description/Galleries.css" type="text/css" rel="Stylesheet" /><link href="description/Layout.css" type="text/css" rel="Stylesheet" /><link href="description/Brand.css" type="text/css" rel="Stylesheet" />
        <link href="description/iframedescription.css" rel="Stylesheet" type="text/css" />
        <script src="description/offline.js" type="text/javascript"></script>
        <style type="text/css">
            #projectInfo {
                overflow: auto;
            }
            #longDesc {
                clear:both;
                margin: 25px 0 10px 0;
            }

            #SampleIndexList{
                margin-left: 15px;
            }
        </style>
    </head>
<body>
    <div id="offlineDescription">
        <h1>Design Patterns - Service Locator Pattern (Inversion of Control &amp; Unity Blocks)</h1>
        <br/>
        <div id="projectInfo">
            <div class="section">
                    <div class="itemBarLong tagsContainer">
                        <label for="Technologies">Technologies</label>
                        <div id="Technologies">
                            Unity Blocks
                        </div>
                    </div>
                    <div class="itemBarLong tagsContainer">
                        <label for="Topics">Topics</label>
                        <div id="Topics">
                            Unity Blocks
                        </div>
                    </div>
                <div class="itemBarLong">
                    <label for="Platforms">Platforms</label>
                    <div id="Platforms">
                        Desktop, Web, Cloud, Data
                    </div>
                </div>
                <div class="itemBarLong">
                    <label for="Requirements">Requirements</label>
                    <div id="Requirements">
                        
                    </div>
                </div>
                <div class="itemBar">
                    <label for="LastUpdated">Primary language</label>
                    <div id="LastUpdated">en-US</div>
                </div>
                <div class="itemBar">
                    <label for="LastUpdated">Updated</label>
                    <div id="LastUpdated">4/30/2013</div>
                </div>
                <div class="itemBarLong">
                    <label for="License">License</label>
                    <div id="License">
                        <a href="license.rtf">Apache License, Version 2.0</a></div>
                </div>
                <div class="itemBar">
                    <div class="viewonlinecont">
                        <a data-link="online" href="http://code.msdn.microsoft.com/Design-Patterns-Inversion-db3283da">View this sample online</a>
                    </div>
                </div>
            </div>
        </div>
        
                   
<script type="text/javascript">
    function initializePage() {
        var otherTabClass = 'otherTab';
        var hiddenPreClass = 'hidden';

        var htmlDecode = function(encodedData) {
            var decodedData = "";
            if (encodedData) {
                var div = document.createElement('div');
                div.innerHTML = encodedData;
                decodedData = div.firstChild.nodeValue.replace( /\\r\\n/ig , '\r\n');
            }
            return decodedData;
        };
                
        Galleries.iterateElem(Galleries.findElem(null, 'div', 'scriptcode'), function (index, scriptBlock) {
            var titleElem = Galleries.findElem(scriptBlock, 'div', 'title')[0];
            var labelElems = Galleries.findElem(titleElem, 'span');
            if (labelElems.length == 0) {
                labelElems = titleElem;
            }
            var languageSpans = Galleries.findElem(scriptBlock, 'span', 'hidden');
            var pres = Galleries.findElem(scriptBlock, 'pre');
            if (languageSpans.length > 0 && pres.length > 1) {
                Galleries.iterateElem(labelElems, function(index, elem) {
                    var codePre = pres[index];
                    var labelSpan = elem;
                    var languageSpan = languageSpans[index];
                            
                    elem.code = codePre.innerHTML.replace( /(\r(\n)?)|((\r)?\n)/ig , '\\r\\n');
                            
                    codePre.className = codePre.className.replace(hiddenPreClass, '');
                            
                    languageSpan.parentNode.removeChild(languageSpan);
                });

                pres = Galleries.findElem(scriptBlock, 'pre');
                Galleries.iterateElem(labelElems, function(index, elem) {
                    var codePre = pres[index];
                    var labelSpan = elem;
                    if (index == 0) {
                        scriptBlock.activeTab = 0;
                    }
                    else {
                        labelSpan.className += otherTabClass;
                        codePre.className += hiddenPreClass;
                    }
                    Galleries.attachEventHandler(labelSpan, 'click', function(e) {
                        var activeTab = scriptBlock.activeTab;
                        labelElems[activeTab].className += otherTabClass;
                        pres[activeTab].className += hiddenPreClass;

                        codePre.className = codePre.className.replace(hiddenPreClass, '');
                        labelSpan.className = labelSpan.className.replace(otherTabClass, '');
                        scriptBlock.activeTab = index;
                    });
                });

                var preview = Galleries.findElem(scriptBlock, 'div', 'preview');
                if (preview.length == 0) {
                    preview.push(pres[pres.length - 1]);
                }
                Galleries.iterateElem(preview, function(index, elem) {
                    elem.parentNode.removeChild(elem);
                });

                if (window.clipboardData && clipboardData.setData) {
                    var copyLink = document.createElement('a');
                    copyLink.href = 'javascript:void(0);';
                    copyLink.className = 'copyCode';
                    copyLink.innerHTML = 'Copy code';
                    Galleries.attachEventHandler(copyLink, 'click', function (e) {
                        clipboardData.setData("Text", htmlDecode(labelElems[scriptBlock.activeTab].code));
                        return false;
                    });
                    scriptBlock.insertBefore(copyLink, scriptBlock.childNodes[0]);
                }
            }
        });
    }

    Galleries.onWindowLoad(function(){
        initializePage();
    });

</script>
<div id="longDesc">
    
<div><span style="color:#ff0000; font-size:small">Work In Progress - I am updating the content and samples parellel.</span></div>
<div><span style="color:#008000; font-size:medium">Targeted Audience:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">1. .NET Architects</span><br>
<span style="font-size:small">2. .NET Application Designers</span><br>
<span style="font-size:small">3. .NET Application Developers</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">Prerequisites:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">1. .Net technologies.</span><br>
<span style="font-size:small">2. Basic understanding of design patterns.</span><br>
<span style="font-size:small">3. Basic understanding of OOPS.</span><br>
<span style="font-size:small">4. Factories (Abstract Factory &amp; Factory Method).</span><br>
<span style="font-size:small">5. Container Pattern.</span><br>
<span style="font-size:small">6. SOLID principles. </span><span style="font-size:small">(Refer
<a href="http://gallery.technet.microsoft.com/OOPS-Principles-SOLID-017627d2">http://gallery.technet.microsoft.com/OOPS-Principles-SOLID-017627d2)</a></span></div>
<div><span style="font-size:small"><span style="color:#000000">7.</span> Read more about Unity blocks here
<a href="http://code.msdn.microsoft.com/Dependency-Injection-with-d9222c2f">http://code.msdn.microsoft.com/Dependency-Injection-with-d9222c2f</a></span></div>
<div><span style="font-size:small">&nbsp;</span>&nbsp;</div>
<div><span style="color:#008000; font-size:medium">Problem Statement:</span></div>
<div><span style="color:#808000; font-size:small"><img id="65389" src="description/1.png" alt="" width="234" height="138"></span></div>
<div>&nbsp;</div>
<div><span style="color:#808000; font-size:small">&nbsp;</span></div>
<div><span style="color:#808000; font-size:small">Tight Coupling: (Compilation time)
</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">We have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB.</span></div>
<div><span style="color:#808000; font-size:small">&nbsp;</span>&nbsp;</div>
<div><span style="color:#808000; font-size:small">This situation has the following problems:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">&bull; To replace or update the dependencies, we need to change the classes' source code.</span><br>
<span style="font-size:small">&bull; The concrete implementations of the dependencies have to be available at compile time.</span><br>
<span style="font-size:small">&bull; Classes are difficult to test in isolation because they have direct references to dependencies. I.e. dependencies cannot be replaced with stubs or mocks.</span><br>
<span style="font-size:small">&bull; Classes contain repetitive code for creating, locating, and managing their dependencies.</span><br>
<span style="font-size:small">&bull; Using Factories (Abstract Factory &amp; Factory Method) creates tight coupling and make application to re compile every time when there is any change in dependencies.</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">Solution:</span></div>
<div><span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&nbsp;</span></span></span><span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&nbsp;</span></span></span></div>
<div><span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&bull; Modular Programming - Loose Coupling (Run time)
</span>Decouple classes from being responsible for locating and managing the lifetime of dependencies.</span><br>
<span style="font-size:small"><span style="font-size:small">&bull; </span>Decouple classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to our classes' source code.
</span><br>
<span style="font-size:small"><span style="font-size:small">&bull; </span>Write classes that depend on classes whose concrete implementation is not known at compile time.
</span><br>
<span style="font-size:small"><span style="font-size:small">&bull; TDD (Test Driven Development)
</span>Should be able to test your classes in isolation, without using the dependencies.</span></span></div>
<div><span style="font-size:small"><span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&bull;
</span></span>Follow the IoC Principle and use the Dependency Injection and Service Locator Patterns.</span></span></div>
<div><img id="68245" src="description/P2.png" alt="" width="374" height="138"></div>
<div></div>
<div><span style="color:#008000; font-size:medium">What is Inversion of Control (IoC)?</span></div>
<div><span style="font-size:small">&ldquo;Inversion&rdquo; refers to inverting or flipping the way we think about the program design in an object oriented way.</span><br>
<span style="font-size:small">Inversion of Control (IoC) is an object-oriented programming principle where the object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.</span><br>
<span style="font-size:small">Many places it is also referred as Design Pattern, but here I would refer it as OOP principle.</span></div>
<div><span style="font-size:small">Refer OOPS SOLID Principles here <a href="http://gallery.technet.microsoft.com/OOPS-Principles-SOLID-017627d2">
http://gallery.technet.microsoft.com/OOPS-Principles-SOLID-017627d2</a></span></div>
<div><span style="font-size:small">In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another.
</span><br>
<span style="font-size:small">With Inversion of Control principle, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions.
</span><br>
<span style="font-size:small">The binding process is achieved through dependency injection and service locator design patterns.</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><img id="65391" src="description/82bf72fb-2ff6-48ab-b2c7-3a296d2f819d2.png" alt="" width="576" height="179"></div>
<div><span style="font-size:small">Conceptual view of the Service Locator and Dependency Injection patterns
</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">IoC Implementation Ways:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">&bull; Using Dependency Injection (a constructor, property setter, an interface injection)</span><br>
<span style="font-size:small">&bull; Using a contextualized lookup</span><br>
<span style="font-size:small">&bull; Using a factory pattern</span><br>
<span style="font-size:small">&bull; Using a service locator pattern</span><br>
<span style="font-size:small">&bull; Using Unity Framework (Constructor, Property, Interface, Service Locator Injections)</span><br>
<span style="font-size:small">&bull; Using Prism Framework (Unity Framework &#43; MEF &#43; Other modular programming features)</span><br>
<span style="font-size:small">&bull; Using Spring.Net, Google Guice (Complicated implementations)</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">Dependency Injection Pattern:</span></div>
<div><span style="color:#000000; font-size:small">&nbsp;</span></div>
<div><span style="color:#000000; font-size:small">Read more about Dependency Injection Pattern
<a href="http://code.msdn.microsoft.com/Dependency-Injection-with-5702acaf">http://code.msdn.microsoft.com/Dependency-Injection-with-5702acaf</a></span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">Service Locator Pattern:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">The service locator (also referred as Anti Pattern) provides a way to register services and it holds references to the services. After the service is registered, the service locator can find the service.</span><br>
<span style="font-size:small">It does not instantiate the services.</span></div>
<div><span style="font-size:small">The service locator should provide a way to locate a service without specifying the concrete type.
</span><br>
<span style="font-size:small">For example, it could use a string key or a service interface type. This enables easy replacement of the dependency concrete implementation without modifying our classes' source code.</span></div>
<div><span style="font-size:small"><span style="font-size:small">&bull; It d</span>ecouple classes from being responsible for locating and managing the lifetime of dependencies.</span><br>
<span style="font-size:small"><span style="font-size:small">&bull; It d</span></span><span style="font-size:small">ecouple classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to our classes' source
 code. </span><br>
<span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&bull; It can w</span></span>rite classes that depend on classes whose concrete implementation is not known at compile time.
</span><br>
<span style="font-size:small"><span style="font-size:small"><span style="font-size:small">&bull;
</span></span></span><span style="font-size:small">Should be able to test your classes in isolation, without using the dependencies.</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">Implementation of Service Locator Pattern:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">The Service Locator pattern can be implemented in several ways. The Unity Application
</span></div>
<div><span style="font-size:small">Block provides a container that can be used as a service locator.</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">What is Unity Application Block:</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">The Unity Application Block (Unity) is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection.</span></div>
<div><span style="font-size:small">Provides simplified object creation, especially for hierarchical object structures and dependencies, which simplifies application code.</span></div>
<div><span style="font-size:small">&nbsp;</span><span style="font-size:small">Supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns (logging, exception
 handling, caching etc).</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">It increases flexibility by deferring component configuration to the container.</span></div>
<div><span style="font-size:small">It has a service location capability; this allows clients to store or cache the container.</span></div>
<div><span style="font-size:small">It especially useful in ASP.NET Web applications, where developers can persist the container in the ASP.NET session or application.</span></div>
<div><span style="font-size:small">Unity is a general-purpose container for use in any type of Microsoft&reg; .NET Framework-based application.</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">Unity is extensible. we can write container extensions that change the behavior of the container, or add new capabilities. For example, the interception feature provided by Unity, which we can use to add policies to objects,
 is implemented as a container extension.</span></div>
<div><span style="font-size:small">&nbsp;</span></div>
<div><span style="font-size:small">Note: Dependency injection provides opportunities to simplify code, abstract dependencies between objects, and automatically generate dependent object instances.</span></div>
<div><span style="font-size:small">However, the process may have a minor impact on performance, and it can increase complexity where only simple dependencies exist.</span></div>
<div><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div><span style="color:#008000; font-size:medium">How Unity Works as Service Locator?</span></div>
<div><span style="color:#000000; font-size:small"><strong>&nbsp;</strong></span></div>
<div><span style="color:#000000; font-size:small"><span style="color:#008080">Unity Container</span> component in Unity blocks acks as a Service locator.</span></div>
<div><span style="color:#000000; font-size:small">1. Required code calls the Resolve method by using container instance.</span></div>
<div><span style="color:#000000; font-size:small">2. Unity Resolves the type and creates the object instance.</span></div>
<div><span style="color:#000000; font-size:small">3. Unity resolves the type of appropriate constructor and method parameters and properties of the object, and injects the resolved dependent object instances into the target object.
</span></div>
<div><span style="color:#000000; font-size:small">4. Unity resolves the type of appropriate constructor and method parameters and properties of all dependent objects, and injects these into the dependent object instances. This process continues for all dependent
 objects.</span></div>
<div><span style="color:#000000; font-size:small">5. Unity returns the fully populated object to the calling code.</span></div>
<div><span style="color:#000000; font-size:small"><img id="68293" src="description/new bitmap image.bmp" alt="" width="568" height="624"></span></div>
<div><strong>&nbsp;</strong></div>
<div><span style="color:#008000; font-size:medium">How to use Unity?</span></div>
<div><span style="color:#000000; font-size:small">&nbsp;</span></div>
<div><span style="color:#000000; font-size:small">Here I am not focusing on how to use unity to understand more about how to use unity read
<a href="http://code.msdn.microsoft.com/Dependency-Injection-with-d9222c2f">http://code.msdn.microsoft.com/Dependency-Injection-with-d9222c2f</a>.
</span></div>
<div><span style="color:#000000; font-size:small"><span style="color:#800000"><span style="color:#008000; font-size:medium">&nbsp;</span></span></span></div>
<div><span style="color:#000000; font-size:small"><span style="color:#800000"><span style="color:#008000; font-size:medium">How to use Unity as Service Locator</span></span></span><span style="color:#000000; font-size:small"><span style="color:#800000"><span style="color:#008000; font-size:medium">?
</span></span></span></div>
<div><span style="color:#000000; font-size:small"><span style="color:#800000"><span style="color:#000000"><span style="color:#808000">Step 1:</span> Add these dll references to console application and write the below using
</span>statement.</span><br>
Microsoft.Practices.Unity.dll &amp; Microsoft.Practices.ObjectBuilder2.dll </span>
</div>
<div><span style="color:#000000">
<div class="endscriptcode"></div>
</span></div>
<div><span style="color:#000000; font-size:small"><span style="color:#808000">Step 2:</span>&nbsp;Setting Up the Unity Container</span></div>
<div class="endscriptcode">
<div><span style="font-size:small"><span style="color:#000080"><span class="cs__keyword">using</span>
<a class="libraryLink" title="Auto generated link to Microsoft.Practices.Unity" href="http://msdn.microsoft.com/en-US/library/Microsoft.Practices.Unity.aspx" >
Microsoft.Practices.Unity</a>; <br>
</span><span style="color:#000000">First create a new instance of the UnityContainer class or use a reference to an existing instance.
</span></span></div>
<div><span style="color:#000080; font-size:small">IUnityContainer myContainer = <span class="cs__keyword">
new</span> UnityContainer();</span></div>
</div>
<div>&nbsp;</div>
<div><span style="color:#000000; font-size:small">
<div><span style="color:#808000">Step 3:</span> Register mappings for a Unity container:</div>
<div class="endscriptcode">
<div><span style="color:#000000"><span style="color:#000080">1. RegisterType: </span>
This method registers a type with the container. At the appropriate time, the container will build an instance of the type we specify. This could be in response to dependency injection through class attributes or when we call the Resolve method.
</span></div>
<div><span style="color:#000000">The target type must implement the interface, or inherit from the class, that we specify as the registered type.</span></div>
<div><span style="color:#000000">E.g. Register a mapping for an interface named IMyService, and specifies that the container should return an instance of the CustomerService class (which implements the IMyService interface).</span></div>
<div><span style="color:#000000"><span style="color:#808000">Step 4:</span> Register a mapping (default) for an interface or class to a concrete type.</span></div>
<div><span style="color:#000080">myContainer.RegisterType&lt;IMyService, CustomerService&gt;();</span></div>
</div>
</span></div>
<div>&nbsp;
<div class="scriptcode">
<div class="pluginEditHolder" pluginCommand="mceScriptCode">
<div class="title"><span>C#</span></div>
<div class="pluginLinkHolder"><span class="pluginEditHolderLink">Edit</span>|<span class="pluginRemoveHolderLink">Remove</span></div>
<span class="hidden">csharp</span>
<pre class="hidden">namespace ServiceLocatorPatternDemo
{
    public interface ILogger
    {
        string WriteMessage(string message);
    }
    public class DemoTextLogger : ILogger
    {
        public string WriteMessage(string message)
        {
            return &quot;DemoTextLogger - '&quot; &#43; message &#43; &quot;'.&quot;;
        }
    }
    public class DemoExceptionLogger : ILogger
    {
        public string WriteMessage(string exceptionMessage)
        {
            return &quot;DemoExceptionLogger - '&quot; &#43; exceptionMessage &#43; &quot;'&quot;;
        }
    }
}

using System;
using <a class="libraryLink" href="http://msdn.microsoft.com/en-US/library/Microsoft.Practices.Unity.aspx"  title="Auto generated link to Microsoft.Practices.Unity">Microsoft.Practices.Unity</a>;

namespace ServiceLocatorPatternDemo
{
    class Program
    {
        static void Main(string[] args)
        {  
            // Step 1 : Create an instance of Unity container. Here it will acts as a Service Locator.
            IUnityContainer UnityContainerObject = new UnityContainer();

            // Step 2 : Use UnityContainerObject and register the ILogger.
            UnityContainerObject.RegisterType&lt;ILogger, ILogger&gt;();

            // Step 2 : Use UnityContainerObject's Resolve method and get instance of DemoTextLogger.
            // Focus more on this step and understand clearly, we are not directly creating instance of DemoTextLogger.
            // So if there is any change in DemoTextLogger (let us assume we are consuming from outside of our project), we will not requireded to change our project code.
            ILogger ILoggerInstance = UnityContainerObject.Resolve&lt;DemoTextLogger&gt;();

            Console.WriteLine(&quot;\n&quot; &#43; ILoggerInstance.WriteMessage(&quot;UnityContainer created the object of type DemoTextLogger&quot;));


            // Step 3 : Use UnityContainerObject's Resolve method and get instance of DemoExceptionLogger.
            // Focus more on this step and understand clearly, we are not directly creating instance of DemoExceptionLogger.
            // So if there is any change in DemoExceptionLogger (let us assume we are consuming from outside of our project), we will not requireded to change our project code.
            ILoggerInstance = UnityContainerObject.Resolve&lt;DemoExceptionLogger&gt;();

            Console.WriteLine(&quot;\n&quot; &#43; ILoggerInstance.WriteMessage(&quot;UnityContainer created the object of type DemoExceptionLogger&quot;));

            Console.ReadLine();
        }
    }
}</pre>
<div class="preview">
<pre class="csharp"><span class="cs__keyword">namespace</span>&nbsp;ServiceLocatorPatternDemo&nbsp;
{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">public</span>&nbsp;<span class="cs__keyword">interface</span>&nbsp;ILogger&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">string</span>&nbsp;WriteMessage(<span class="cs__keyword">string</span>&nbsp;message);&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">public</span>&nbsp;<span class="cs__keyword">class</span>&nbsp;DemoTextLogger&nbsp;:&nbsp;ILogger&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">public</span>&nbsp;<span class="cs__keyword">string</span>&nbsp;WriteMessage(<span class="cs__keyword">string</span>&nbsp;message)&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">return</span>&nbsp;<span class="cs__string">&quot;DemoTextLogger&nbsp;-&nbsp;'&quot;</span>&nbsp;&#43;&nbsp;message&nbsp;&#43;&nbsp;<span class="cs__string">&quot;'.&quot;</span>;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">public</span>&nbsp;<span class="cs__keyword">class</span>&nbsp;DemoExceptionLogger&nbsp;:&nbsp;ILogger&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">public</span>&nbsp;<span class="cs__keyword">string</span>&nbsp;WriteMessage(<span class="cs__keyword">string</span>&nbsp;exceptionMessage)&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">return</span>&nbsp;<span class="cs__string">&quot;DemoExceptionLogger&nbsp;-&nbsp;'&quot;</span>&nbsp;&#43;&nbsp;exceptionMessage&nbsp;&#43;&nbsp;<span class="cs__string">&quot;'&quot;</span>;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
}&nbsp;
&nbsp;
<span class="cs__keyword">using</span>&nbsp;System;&nbsp;
<span class="cs__keyword">using</span>&nbsp;<a class="libraryLink" href="http://msdn.microsoft.com/en-US/library/Microsoft.Practices.Unity.aspx"  title="Auto generated link to Microsoft.Practices.Unity">Microsoft.Practices.Unity</a>;&nbsp;
&nbsp;
<span class="cs__keyword">namespace</span>&nbsp;ServiceLocatorPatternDemo&nbsp;
{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">class</span>&nbsp;Program&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__keyword">static</span>&nbsp;<span class="cs__keyword">void</span>&nbsp;Main(<span class="cs__keyword">string</span>[]&nbsp;args)&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Step&nbsp;1&nbsp;:&nbsp;Create&nbsp;an&nbsp;instance&nbsp;of&nbsp;Unity&nbsp;container.&nbsp;Here&nbsp;it&nbsp;will&nbsp;acts&nbsp;as&nbsp;a&nbsp;Service&nbsp;Locator.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;IUnityContainer&nbsp;UnityContainerObject&nbsp;=&nbsp;<span class="cs__keyword">new</span>&nbsp;UnityContainer();&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Step&nbsp;2&nbsp;:&nbsp;Use&nbsp;UnityContainerObject&nbsp;and&nbsp;register&nbsp;the&nbsp;ILogger.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;UnityContainerObject.RegisterType&lt;ILogger,&nbsp;ILogger&gt;();&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Step&nbsp;2&nbsp;:&nbsp;Use&nbsp;UnityContainerObject's&nbsp;Resolve&nbsp;method&nbsp;and&nbsp;get&nbsp;instance&nbsp;of&nbsp;DemoTextLogger.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Focus&nbsp;more&nbsp;on&nbsp;this&nbsp;step&nbsp;and&nbsp;understand&nbsp;clearly,&nbsp;we&nbsp;are&nbsp;not&nbsp;directly&nbsp;creating&nbsp;instance&nbsp;of&nbsp;DemoTextLogger.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;So&nbsp;if&nbsp;there&nbsp;is&nbsp;any&nbsp;change&nbsp;in&nbsp;DemoTextLogger&nbsp;(let&nbsp;us&nbsp;assume&nbsp;we&nbsp;are&nbsp;consuming&nbsp;from&nbsp;outside&nbsp;of&nbsp;our&nbsp;project),&nbsp;we&nbsp;will&nbsp;not&nbsp;requireded&nbsp;to&nbsp;change&nbsp;our&nbsp;project&nbsp;code.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ILogger&nbsp;ILoggerInstance&nbsp;=&nbsp;UnityContainerObject.Resolve&lt;DemoTextLogger&gt;();&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine(<span class="cs__string">&quot;\n&quot;</span>&nbsp;&#43;&nbsp;ILoggerInstance.WriteMessage(<span class="cs__string">&quot;UnityContainer&nbsp;created&nbsp;the&nbsp;object&nbsp;of&nbsp;type&nbsp;DemoTextLogger&quot;</span>));&nbsp;
&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Step&nbsp;3&nbsp;:&nbsp;Use&nbsp;UnityContainerObject's&nbsp;Resolve&nbsp;method&nbsp;and&nbsp;get&nbsp;instance&nbsp;of&nbsp;DemoExceptionLogger.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;Focus&nbsp;more&nbsp;on&nbsp;this&nbsp;step&nbsp;and&nbsp;understand&nbsp;clearly,&nbsp;we&nbsp;are&nbsp;not&nbsp;directly&nbsp;creating&nbsp;instance&nbsp;of&nbsp;DemoExceptionLogger.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="cs__com">//&nbsp;So&nbsp;if&nbsp;there&nbsp;is&nbsp;any&nbsp;change&nbsp;in&nbsp;DemoExceptionLogger&nbsp;(let&nbsp;us&nbsp;assume&nbsp;we&nbsp;are&nbsp;consuming&nbsp;from&nbsp;outside&nbsp;of&nbsp;our&nbsp;project),&nbsp;we&nbsp;will&nbsp;not&nbsp;requireded&nbsp;to&nbsp;change&nbsp;our&nbsp;project&nbsp;code.</span>&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ILoggerInstance&nbsp;=&nbsp;UnityContainerObject.Resolve&lt;DemoExceptionLogger&gt;();&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine(<span class="cs__string">&quot;\n&quot;</span>&nbsp;&#43;&nbsp;ILoggerInstance.WriteMessage(<span class="cs__string">&quot;UnityContainer&nbsp;created&nbsp;the&nbsp;object&nbsp;of&nbsp;type&nbsp;DemoExceptionLogger&quot;</span>));&nbsp;
&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.ReadLine();&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;
}</pre>
</div>
</div>
</div>
<div class="endscriptcode"><span style="color:#008000; font-size:medium">Additional Reference Links:</span></div>
<div class="endscriptcode"><span style="color:#008000; font-size:small">&nbsp;</span></div>
<div class="endscriptcode"><span style="color:#008000; font-size:small"><a href="http://martinfowler.com/articles/injection.html">http://martinfowler.com/articles/injection.html</a></span></div>
<div class="endscriptcode"><span style="color:#008000; font-size:small"><a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx</a></span></div>
<div class="endscriptcode"><span style="color:#008000; font-size:medium">&nbsp;</span></div>
<div class="endscriptcode"><span style="color:#008000; font-size:medium">Disadvantages of Service Locator pattern:</span></div>
</div>
<div><span style="font-size:small">1. There are more solution elements to manage.
</span><br>
<span style="font-size:small">2. We have to write additional code to add service references to the locator before our objects use it.
</span><br>
<span style="font-size:small">3. The source code has added complexity; this makes the source code more difficult to understand.</span><br>
<span style="font-size:small">4. Slight performance issues.</span><br>
<span style="font-size:small">5. Little difficult in debugging.</span></div>
<div>
<div class="endscriptcode"><span style="color:#000000; font-size:small"><span style="color:#ff0000">&nbsp;</span></span></div>
<span style="color:#000000; font-size:small"><span style="color:#ff0000">Work In Progress -&nbsp;I am&nbsp;still updating the article in parallel mean while download and drop your questions in QA tab.</span></span><span style="font-size:small">
<div class="endscriptcode"></div>
<span style="color:#808000; font-size:small">
<div class="endscriptcode"><span style="color:#000000; font-size:small">&nbsp;</span></div>
<div class="endscriptcode"><span style="color:#000000; font-size:small">Thank you for reading my article. Drop all your questions/comments in QA tab give me your feedback with
<span style="color:#3366ff"><img id="67168" src="description/Ratings.png" alt="" width="74" height="15">
<span style="color:#000000">star rating (1 Star - Very Poor, 5&nbsp;Star -&nbsp;Very Good).
</span></span></span></div>
<div class="endscriptcode"><span style="color:#3366ff">&nbsp;</span></div>
<div class="endscriptcode"></div>
<div class="endscriptcode"><span style="color:#808000; font-size:small">Visit my all other articles here
<a href="http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=User&amp;f%5B0%5D.Value=Srigopal%20Chitrapu">
http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=User&amp;f%5B0%5D.Value=Srigopal%20Chitrapu</a></span></div>
</span></span></div>

</div>


    </div>
</body>
</html>
